-- UISkyShop
-- Create by huanghr
-- 天空商店界面

require "game/ui/form/hero/HeroUtil"
require "game/ui/form/sky_city/UISkyShopGoodsInfo"

-- UISkyShop继承自Layer
UISkyShop = class("UISkyShop", function()
    return cc.Layer:create();
end);

function UISkyShop.create()
    return UISkyShop.new();
end

-- 商品格最大行数和列数
local MAX_GRID_ROW    = 2;
local MAX_GRID_COLUMN = 3;

-- 商品类型
local TREASURE = 6;
local ROBOT = 8;

-- 超过一分钟没有更新主动请求数据
local SECONDS_PER_MIN = 60;
-- 最大请求次数
local MAX_TYR_TIME = 10;

-- 内部函数声明

-- 构造函数
function UISkyShop:ctor()
    -- 初始化
    self:setName("UISkyShop");
    local node = cc.CSLoader:createNode("layout/shop/BlackMarket.csb");
    self:addChild(node);
    self.node = node;

    local CT = node:getChildByName("CT");
    local scrollview = CT:getChildByName("scroll_view");
    self.CT = CT;
    self.scrollView = scrollview;
    self.scrollView:setVisible(true);

    -- 水平滑动，需要显示左右蒙版
    local mask3 = findChildByName(self.node, "CT/mask3");
    mask3:setVisible(true);
    local mask4 = findChildByName(self.node, "CT/mask4");
    mask4:setVisible(true);

    -- 修改滚动方向
    -- 1 垂直
    -- 2 水平
    self.scrollView:setDirection(2);

    -- 尝试请求次数
    self.hasTry = 0;

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 初始化商品格子
    self:initGoodsGrids(self.node);

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UISkyShop:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 初始化商品格
function UISkyShop:initGoodsGrids(node)
    local w = DESIGN_WIDTH;
    local h = DESIGN_HEIGHT;

    -- 图标间距(横向)
    local wGap = 23;

    -- 图标间距(纵向)
    local hGap = 33;

    -- 图标宽度
    local iconWidth = 128;

    -- 图片高度
    local iconHeight = 163;

    local topHGap  = 100;
    local leftWGap = 20;

    -- 收集商品信息
    local goodsList = self:gatherGoodsInfo();

    -- 商品的共个数
    local shopCount = #goodsList;

    self.scrollView.rows = {};
    self.scrollView:removeAllChildren();

    local itemNode = cc.CSLoader:createNode("layout/shop/BlackMarketGoodsIcon.csb");
    -- @param windowNode    界面节点
    -- @param scrollNode    容器节点
    -- @param itemNode      单元格的节点
    -- @param totalNum      单元格总数
    -- @param maxRowNum     最大行数
    -- @param pageColNum    单页可以显示下的列数
    -- @param wGap          单元格间距(横向) 这里作为最小值使用
    -- @param hGap          单元格间距(纵向)
    -- @param iconWidth     单元格宽度
    -- @param iconHeight    单元格高度
    -- @param topHGap       上方留
    -- @param leftWGap      左右留白  这里作为最小值使用
    -- @param touchEvent    点击事件注册函数
    initScrollGridsHorizontal(self, self.scrollView, itemNode, shopCount, MAX_GRID_ROW, MAX_GRID_COLUMN, wGap, hGap, iconWidth, iconHeight, topHGap, leftWGap, self.registerItemTouchEvent);
end

-- 清空所有的商品格
function UISkyShop:clearAllGrid()
    -- 格子总数
    local totalGridCount = MAX_GRID_ROW * MAX_GRID_COLUMN;
    for i = 1, totalGridCount do
        local grid = self.scrollView:getChildByName("item" .. i);
        if grid then
            grid:setVisible(false);
        end
    end
end

-- 显示商店
function UISkyShop:redraw()
    -- 显示标题
    local titleLabel = findChildByName(self.CT, "title");
    TextStyleM.setTitleStyle(titleLabel);
    titleLabel:setString(getLocStr("btn_text_sky_shop"));

    -- 绘制倒计时
    self:redrawTime();

    -- 收集商品信息
    local goodsList = self:gatherGoodsInfo();
    local totalGridCount = #goodsList;

    if not goodsList or #goodsList == 0 then
        cclog("收集商品信息失败。");
        self:clearAllGrid();
        return;
    end
    -- 显示商品信息
    local totalGoodsCount = #goodsList;
    for i = 1, totalGridCount do
        local grid          = self.scrollView:getChildByName("item" .. i);
        local goodsBg       = grid:getChildByName("bg");
        local iconImg       = grid:getChildByName("goods_icon");
        local moneyImg      = grid:getChildByName("money_icon");
        local moneyLabel    = grid:getChildByName("money_count");
        local soldOutLabel    = grid:getChildByName("sold_out");
        local rankNode      = grid:getChildByName("star_node");
        local countLabel     = grid:getChildByName("item_count");

        if i <= totalGoodsCount then
            grid:setVisible(true);

            local goodsIndex = goodsList[i][1]    -- 商品序号
            local goodsId    = goodsList[i][2];   -- 商品id
            local goodsIcon  = goodsList[i][3];   -- 商品图标
            local payAttrib  = goodsList[i][4];   -- 支付属性
            local goodsPrice = goodsList[i][5];   -- 商品价格
            local goodsCount = goodsList[i][6];   -- 商品数量
            local itemName   = goodsList[i][7];   -- 物品名称
            local itemDesc   = goodsList[i][8];   -- 物品描述
            local soldOut    = goodsList[i][9];   -- 是否售完
            local rank       = goodsList[i][10];  -- 阶位
            local classify   = goodsList[i][11];  -- 类别
            local payType  = goodsList[i][12];  -- 支付类别

            -- 为商品图标绑定信息
            iconImg.goodsIndex = goodsIndex;
            iconImg.goodsId    = goodsId;
            iconImg.goodsIcon  = goodsIcon;
            iconImg.payAttrib  = payAttrib;
            iconImg.goodsPrice = goodsPrice;
            iconImg.goodsCount = goodsCount;
            iconImg.itemName   = itemName;
            iconImg.itemDesc   = itemDesc;
            iconImg.soldOut    = soldOut;
            iconImg.rank       = rank;
            iconImg.payType    = payType;

            -- 显示商品阶位
            if classify ~= "honor_scrap" then
                local goods = ShopM.queryGoodsInfo(iconImg.goodsId);

                local goodsType = goods[1];
                local classId = goods[2];
                local needShow = false;
                if goodsType == ROBOT then
                    needShow = true;
                else
                    needShow = FormulaM.invoke("NEED_SHOW_STAR", classId);
                end
                if needShow then
                    local layer = createStarLayer(rank, "images/ui/symbol/star_little.png", "center", -0.7);
                    if layer then
                        rankNode:removeAllChildren();
                        rankNode:addChild(layer);
                    end
                end
            end

            -- 显示商品名称和数量
            TextStyleM.setTextStyle(countLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, -2);
            if goodsCount > 1 then
                -- 需要显示数量
                countLabel:setString(tostring(goodsCount));
            else
                countLabel:setVisible(false);
            end

            -- 显示商品图标
            if classify == "treasure" then
                iconImg:loadTexture(getAirShipSkillIconPath(goodsIcon));
            elseif classify == "robot" then
                iconImg:loadTexture(getRobotIconPath(goodsIcon));
            else
                iconImg:loadTexture(getItemIconPath(goodsIcon));
            end

            -- 显示价格
            local offset = 0;
            local iconPath;

            -- 属性支付
            if 2 == payType then
                iconPath = getSmallAttribIconPath(FieldsM.query(payAttrib, "icon"));
                moneyImg:loadTexture(iconPath);
                moneyImg:setScale(0.83);
                offset = 5;
            elseif 1 == payType then
                -- 物品支付
                iconPath = getItemIconPath(ItemM.query(payAttrib, "icon"));
                moneyImg:setScale(0.45);
                moneyImg:loadTexture(iconPath);
            end

            TextStyleM.setTextStyle(moneyLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_WHITE, true);
            moneyLabel:setString(tostring(goodsPrice));
            moneyLabel:getVirtualRenderer():setAdditionalKerning(getLocKerning() -3);

            if 2 == payType then
                if ME.user:queryAttrib(payAttrib) < goodsPrice then
                    moneyLabel:setTextColor(TextStyleM.TEXT_COLOR_LIGHT_RED);
                else
                    moneyLabel:setTextColor(TextStyleM.TEXT_COLOR_WHITE);
                end
            else
                if ItemM.getAmount(ME.user, payAttrib) < goodsPrice then
                    moneyLabel:setTextColor(TextStyleM.TEXT_COLOR_LIGHT_RED);
                else
                    moneyLabel:setTextColor(TextStyleM.TEXT_COLOR_WHITE);
                end
            end

            -- 居中显示
            local moneyImgW = moneyImg:getContentSize().width * moneyImg:getScaleX();
            local moneyLabelW = moneyLabel:getContentSize().width;
            -- 间隔
            local gap = 5;
            local s = (moneyImgW + moneyLabelW + gap) / 2;
            -- 位置调整
            moneyImg:setPositionX(-s - offset / 2 );
            moneyLabel:setPositionX(moneyImg:getPositionX() + offset + moneyImgW + gap);

            -- 如果商品已售完，显示图标
            if soldOut then
                -- 背景变灰
                setGrayTransMode(goodsBg, true);
                setGrayTransMode(iconImg, true);

                -- 不显示价格、星星
                moneyImg:setVisible(false);
                moneyLabel:setVisible(false);
                rankNode:setVisible(false);

                -- 显示已出售字样
                soldOutLabel:setVisible(true);
                TextStyleM.setTextStyle(soldOutLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_ORANGE, true);
                soldOutLabel:getVirtualRenderer():setAdditionalKerning(getLocKerning() -3);
                soldOutLabel:setString(getLocStr("has_been_sold"));
            else
                -- 背景变亮
                setGrayTransMode(goodsBg, false);
                setGrayTransMode(iconImg, false);

                -- 显示图标、价格、星星
                moneyImg:setVisible(true);
                moneyLabel:setVisible(true);
                rankNode:setVisible(true);

                soldOutLabel:setVisible(false);
            end
        else
            -- 清空多余的格子
            grid:setVisible(false);
        end
    end
end

-- 主动请求数据
function UISkyShop:tryRefresh()
    Operation.cmd_try_refresh_sky_city_shop();
    self.hasTry = self.hasTry + 1;
end

-- 绘制时间
function UISkyShop:redrawTime()
    if self.isTick then
        return;
    end
    local function tick()
        -- 提示信息
        local leftTime = ShopM.getShopAutoRefreshLeftTime("sky_shop");
        local txt1Label = findChildByName(self.CT, "subhead");

        if leftTime <= - SECONDS_PER_MIN
            and math.floor(leftTime % 10) == 0 and self.hasTry < MAX_TYR_TIME then
            -- 更新时间超过一分钟，主动请求更新一次
            self:tryRefresh();
        end

        TextStyleM.setSubheadStyle(txt1Label);
        txt1Label:setString(string.format(getLocStr("black_market_auto_refresh"), remainingTimeDesc(leftTime)));

        performWithDelay(self, tick, 1);
    end
    self.isTick = true;
    tick();
end

-- 获取可购买的商品信息
function UISkyShop:gatherGoodsInfo()
    -- 获取本店的所有商品
    local goodsList = ShopM.getAllGoods("sky_shop");
    if goodsList == nil then
        return nil;
    end

    local ret = {};
    local goodsIndex = 1;  -- 商品的序号
    for _, info in pairs(goodsList) do
        local goodsInfo;
        local arr;
        local goodsId    = info.goods_id;
        if info.goods_type == "honor_scrap" then
            goodsInfo = info.goods;
            arr = ShopM.parseGoodsPrice(info.price);
        else
            goodsInfo = ShopM.queryGoodsInfo(goodsId);
            local priceIndex = info.price;
            arr        = ShopM.queryPrice(goodsId, priceIndex);
        end
        local payType    = arr[1];           -- 支付类型(1:道具，2:属性)
        local payAttrib  = arr[2];           -- 支付属性
        local goodsPrice = arr[3];           -- 商品价格
        local soldOut    = iif(info["sold_out"], info["sold_out"], false);
        local classId    = goodsInfo[2];
        local goodsCount = goodsInfo[3];      -- 商品数量
        local goodsType  = goodsInfo[1];

        local itemInfo;

        if goodsType == TREASURE then
            itemInfo = SkyShipSkillM.query(classId);
        elseif goodsType == ROBOT then
            itemInfo = SkyRobotM.query(classId);
        else
            itemInfo = ItemM.query(classId);
        end

        if info.goods_type == "honor_scrap" then
            classify = "honor_scrap";
        else
            classify   = ShopM.queryClassify(goodsId);
        end

        if itemInfo then
            table.insert(ret, {goodsIndex, goodsId, itemInfo["icon"], payAttrib, goodsPrice, goodsCount,
                itemInfo["name"], itemInfo["desc"], soldOut, itemInfo["rank"], classify, payType});
        end

        goodsIndex = goodsIndex + 1;
    end

    return ret;
end

-- 注册商品点击事件
function UISkyShop:registerItemTouchEvent(node)
    -- 注册商品图标点击事件
    local image = node:getChildByName("bg");
    local iconImg = node:getChildByName("goods_icon");
    local function onClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 仅处理非空的格子
            if type(iconImg.goodsIcon) == 'number' then
                self:onGoodsClick(iconImg);
                AudioM.playFx("button_spell");
            end
        end
    end
    image:addTouchEventListener(onClick)
end

-- 注册事件处理回调函数
function UISkyShop:registerEventCallback()

    -- 关注购买商品的事件
    EventMgr.register("UISkyShop", event.BUY_SHOP_GOODS, function(args)
        local goodsId = args.goodsIndex;
        local shopType = args.shopType;

        self:whenBuyGoods(shopType, goodsId);
    end);

    -- 关注商店信息更新事件
    EventMgr.register("UISkyShop", event.SHOP_DATA_REFRESH, function()
        if UIMgr.getCurrentScene():isOpen("UISkyShop") then
            -- 初始化商品格子
            self:initGoodsGrids(self.node);

            self:redraw();
        end
    end);

    -- 注册获得焦点的回调
    EventMgr.register("UISkyShop", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UISkyShop" then
            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_FIRST_RUINS_SCRAP, TOPMENU_FRAME_GEM, TOPMENU_FRAME_HEAD_AIRSHIP);
        end
    end);

    -- 可能会直接购买碎片
    EventMgr.register("UISkyShop", event.DIRECT_BUY_GOODS, function(args)
        -- 提示购买的数量
        alertBuyGoodsTip(args.bonus);
        self:redraw();
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            EventMgr.removeAll("UISkyShop");

            if UIMgr:getCurrentScene():isOpen("UISkyResource") then
                local uiForm = UIMgr:getCurrentScene():getFormByName("UISkyResource");
                uiForm:refreshItem();
            end
        end
    end);
end

-- 注册点击事件
function UISkyShop:registerTouchEvent()
    -- 注册刷新按钮点击事件
    local btnRefresh = findChildByName(self.node, "BT/refresh");
    local function onRefreshClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("ship_click");

            -- 计算刷新消耗
            local times = ShopM.getShopRefreshCount("sky_shop");
            local cost = FormulaM.invoke("CALC_SHOP_REFRESH_COST", ME.user, "sky_shop", times);
            local needGemNum = cost[1][3];

            local okFunc = function()
                if ShopM.canRefreshGoods("sky_shop") ~= true then
                    showGemLackConfirm();
                    return;
                end

                Operation.cmd_refresh_shop("sky_shop");
            end

            local msg = string.format(getLocStr("black_market_refresh_confirm"), needGemNum, times);
            confirm2(CONFIRM_TYPE_OK, getLocStr("refresh_black_market"), msg,
                okFunc, nil, getLocStr("btn_text_refresh"));
        end
    end
    btnRefresh:addTouchEventListener(onRefreshClick);
    TextStyleM.setTextStyle(btnRefresh, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnRefresh:setTitleText(getLocStr("btn_text_refresh"));
    btnRefresh:setVisible(false);

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("ship_return");
            UIMgr.getCurrentScene():removeFormByName("UISkyShop");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
end

-- 当商品被点击
function UISkyShop:onGoodsClick(iconImg)
    if iconImg.soldOut then
        alert(getLocStr("goods_sold_out"));
        return;
    end

    -- 显示商品详细信息
    local uiGoodsDetail = UISkyShopGoodsInfo.create("sky_shop", iconImg.goodsIndex - 1);
    UIMgr.getCurrentScene():addForm(uiGoodsDetail);
end

-- 关闭购买商品的消息
function UISkyShop:whenBuyGoods(shopType, goodsIndex)
    -- 刷新界面
    self:redraw();

    -- 提示玩家购买了商品
    local function delay()
        local goodsInfo   = ShopM.getGoodInfoInShop(shopType, goodsIndex);
        local arr;
        if goodsInfo.goods_type == "honor_scrap" then
            arr = goodsInfo.goods;
        else
            arr = ShopM.queryGoodsInfo(goodsInfo.goods_id);
        end

        local count = arr[3];
        local name;
        if arr[1] == 1 then
            name = ItemM.query(arr[2], "name");
        elseif arr[1] == ROBOT then
            name = SkyRobotM.query(arr[2], "name");
        else
            name = SkyShipSkillM.query(arr[2], "name");
        end
        alert(string.format(getLocStr("buy_goods_done"), name, count));
    end

    performWithDelay(self, delay, 0.1);
end